package com.simple.base.controller;

import com.alibaba.fastjson.JSON;
import com.simple.base.common.exception.BizException;
import com.simple.base.common.result.BaseResultCode;
import com.simple.base.common.result.CommonResult;
import com.simple.base.common.utils.JWTUtils;
import com.simple.base.common.utils.ResultUtils;
import com.simple.base.core.repository.entity.SysUser;
import com.simple.base.core.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author kin
 * @since 2017/12/25
 */
@RestController
@RequestMapping("/api/sys/user")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public CommonResult login(@RequestParam("username") String username,
                              @RequestParam("password") String password) {
        SysUser sysUser = sysUserService.login(username, password);
        return ResultUtils.ok(JWTUtils.sign(JSON.toJSONString(sysUser), sysUser.getPassword()));
    }

    @RequiresPermissions(value = "sys:user:list")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public CommonResult list() {
        List<SysUser> userList = sysUserService.selectList(null);
        return ResultUtils.ok(userList);
    }

    @RequiresPermissions(value = "sys:user:save")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public CommonResult save(@RequestBody SysUser user) {
        if (StringUtils.isEmpty(user.getAccount())) {
            throw new BizException(BaseResultCode.INVALID_PARAMETER);
        }
        user.setTenantId(1L);
        sysUserService.insert(user);
        return ResultUtils.ok();
    }

    @RequestMapping(value = "delete/{userId}", method = RequestMethod.POST)
    public CommonResult delete(@PathVariable("userId") long userId) {
        sysUserService.deleteById(userId);
        return ResultUtils.ok();
    }
}
